<?php
tsLoad('/core/CoreLib/AbstractMysqlPage.class.php');
class SysRolePage extends AbstractMysqlPage {
	
	/**
	 * 查询所有角色信息
	 */
	public function queryRoles($condition){
		global $mysqlTools;
		//查询所有角色信息
		$children = $mysqlTools->selectSql("
				SELECT
					sr.roleId as id,
					sr.roleName,
					sr.roleDesc as name,
					sr.roleOrder,
					sr.roleCreatetime,
					sr.userId,
					sr.roleIsUsed,
					CASE WHEN (sur.userId is not null) THEN 'true' ELSE 'false' END as checked
				FROM
					sys_role sr left join (select roleId,userId from sys_user_role where userId=$condition[userId]) sur on sr.roleId=sur.roleId
				where
					sr.roleIsUsed=1
				order by sr.roleOrder asc
		");
		return $children;
	}
	
	/**
	 * 取得总的行数
     */
    protected function calTotalRows ()
    {
        global $mysqlTools;
        
        $condition =  $mysqlTools->check_input($this->condition,array('roleName'));
        
        $sqlCore = "
        	SELECT count(*) as totalCount FROM sys_role 
        ";
        
        $where = "
         	where 1 = 1
        ";
        
    	//角色名查询
        if(!empty($condition['roleName'])){
            $where.= ' AND  roleName LIKE '.$condition['roleName'];
        }
        
        //查看状态
        if(!empty($condition['roleIsUsed']) && $condition['roleIsUsed']!=3){
        	$where.= ' AND roleIsUsed ='.$condition['roleIsUsed'];
        }
        
        //创建开始时间与结束时间
        if(!empty($condition['createtimeStart'])){
        	$where.= ' AND roleCreatetime >='.$condition['createtimeStart'];
        }
        if(!empty($condition['createtimeEnd'])){
        	$where.= ' AND roleCreatetime ='.$condition['createtimeEnd'];
        }
        
        //id条件
        if(!empty($condition['roleId']))
            $where.= ' and roleId ='.$condition['roleId'];
        
        $sql = $sqlCore.$where;
        
        //总记录数
        $totalRows = $mysqlTools->selectSql($sql)[0]['totalCount'];
        
        
        return $totalRows;
    }
	
    /**
     *根据roleId查询role信息
     */
    public function queryRoleInfoByRoleId ($condition)
    {
    	global $mysqlTools;
    
    	$sqlCore = "
        	SELECT
				roleId,
				roleName,
				roleDesc,
				roleOrder,
				roleCreatetime,
				userId,
				roleIsUsed,
    			roleType,
    			roleUpgradeCount,
    			roleLevel
			FROM
				sys_role
        ";
    
    	$where = "
         	WHERE roleId = $condition[roleId]
        ";
    
    	$sql = $sqlCore.$where;
    	//查询角色信息
    	$roleInfo = $mysqlTools->selectSql($sql);
    
    	return $roleInfo;
    }
    
    /**
     *根据roleId修改role信息
     */
    public function updateRoleInfoByRoleId ($condition)
    {
    	global $mysqlTools;
    	
    	//参数处理注入SQL安全问题
    	$condition = $mysqlTools->check_input($condition);
    	try {
    		$sql = "UPDATE sys_role SET roleId = roleId";
    		if(!empty($condition['roleName'])){
    			$sql.= ",roleName = $condition[roleName]";
    		}
    		if(!empty($condition['roleDesc'])){
    			$sql.= ",roleDesc = $condition[roleDesc]";
    		}
    		if(!empty($condition['roleOrder'])){
    			$sql.= ",roleOrder = $condition[roleOrder]";
    		}
    		if(!empty($condition['roleIsUsed'])){
    			$sql.= ",roleIsUsed = $condition[roleIsUsed]";
    		}
    		if(!empty($condition['roleType'])){
    			$sql.= ",roleType = $condition[roleType]";
    		}
    		if(!empty($condition['roleUpgradeCount'])){
    			$sql.= ",roleUpgradeCount = $condition[roleUpgradeCount]";
    		}
    		if(!empty($condition['roleLevel'])){
    			$sql.= ",roleLevel = $condition[roleLevel]";
    		}
    		$sql.=" where roleId = $condition[roleId]";
    		
    		$mysqlTools->startTransaction();
    		$result = $mysqlTools->executeSql($sql);
    		$mysqlTools->commitTransaction();
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    	}
    	return $result;
    }
    
	/** 
     *取得数据集合
     */
    protected function getList ($sRowNo, $pageRows)
    {
        global $mysqlTools;

        $orgCondition = $this->condition;
        $condition =  $mysqlTools->check_input($this->condition,array('roleName'));
        
        $sqlCore = "
        	SELECT
				sr.roleId,
				sr.roleName,
				sr.roleDesc,
				sr.roleOrder,
				sr.roleCreatetime,
				sr.userId,
				sr.roleIsUsed,
        		su.userLoginId
			FROM
				sys_role sr left join sys_user su on sr.userId=su.userId
        ";
        
        $where = "
         	WHERE 1 = 1
        ";
        
    	//角色名查询
        if(!empty($condition['roleName'])){
            $where.= ' AND  sr.roleName LIKE '.$condition['roleName'];
        }
        
        //查看状态
        if(!empty($condition['roleIsUsed']) && $condition['roleIsUsed']!=3){
        	$where.= ' AND sr.roleIsUsed ='.$condition['roleIsUsed'];
        }
        
        //创建开始时间与结束时间
        if(!empty($condition['createtimeStart'])){
        	$where.= ' AND sr.roleCreatetime >='.$condition['createtimeStart'];
        }
        if(!empty($condition['createtimeEnd'])){
        	$where.= ' AND sr.roleCreatetime ='.$condition['createtimeEnd'];
        }
        
        //id条件
        if(!empty($condition['roleId']))
            $where.= ' AND sr.roleId = '.$condition['roleId'];
        
        if(!empty($orgCondition['order']) && !empty($orgCondition['sort']))
        	$order = " ORDER BY sr.".$orgCondition['sort']." ".$orgCondition['order']." ";
        else 
        	$order = " ORDER BY sr.roleCreatetime ASC ";
        
        $limit = " LIMIT $sRowNo,$pageRows";
        $sql = $sqlCore.$where.$order.$limit;
        //查询角色信息分页
        $list = $mysqlTools->selectSql($sql);
        //为每个角色查询当前的权限信息
        foreach ($list as $i=>$role){
        	$menus = $mysqlTools->selectSql("select sm.menuDesc from sys_role_menu rm left join sys_menu sm on rm.menuId=sm.menuId where rm.roleId = $role[roleId]");
        	$menuStrs = "";
        	if(!empty($menus))
	        	foreach ($menus as $menu){
	        		$menuStrs .= $menu['menuDesc'].',';
	        	}
        	$list[$i]['menuStrs'] = $menuStrs;
        }
        
        return $list;
    }
    /**
     * 添加角色
     */
    public function addRole($condition){
    	global $mysqlTools,$userSession;
    	//生成唯一ID
    	$uniqid = getCurrentId();
    	
    	//参数处理注入SQL安全问题
    	$condition = $mysqlTools->check_input($condition);
    	try {
    		$userId = $userSession->getUserSession()['userId'];
    		$mysqlTools->startTransaction();
    		$result = $mysqlTools->executeSql("
    				INSERT INTO sys_role
					(
	    				roleId,
	    				roleName,
	    				roleDesc,
    					roleOrder,
    					roleCreatetime,
    					userId,
    					roleIsUsed,
    					roleType,
    					roleUpgradeCount,
    					roleLevel
					)VALUES(
    					$uniqid,
						$condition[roleName],
    					$condition[roleDesc],
    					$condition[roleOrder],
    					NOW(),
    					$userId,
						1,
    					$condition[roleType],   
    					$condition[roleUpgradeCount],
    					$condition[roleLevel]			
					)
			");
    		$mysqlTools->commitTransaction();
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    	}
    	return $result;
    }
    
    /**
     * 删除角色菜单
     */
    public function delRoleMenu($condition){
    	global $mysqlTools;
    	//参数处理注入SQL安全问题
    	$result = true;
    	if(array_key_exists('del',$condition) && empty($condition['del'])){
    		return $result;
    	}
    	$list = explode(',',$condition['del']);
    	$condition = $mysqlTools->check_input($condition);
    	if(!empty($condition['del'])){
    		foreach ($list as $menuId){
    			$res = $mysqlTools->executeSql("
    					DELETE FROM `sys_role_menu`
    					WHERE `menuId` = $menuId AND `roleId` = $condition[roleId]
    					");
    			if(!$res){
    				$result = false;
    			}
    		}
    	}
    	return $result;
    }
    
    /**
     * 添加角色用户
     */
    public function addRoleUser($condition){
    	global $mysqlTools;
    	//参数处理注入SQL安全问题
    	$result = true;
    	if(array_key_exists('add',$condition) && empty($condition['add'])){
    		return $result;
    	}
    	$list = explode(',',$condition['add']);
    	$condition = $mysqlTools->check_input($condition);
    	if(!empty($condition['add'])){
    		foreach ($list as $userId){
    			//生成唯一ID
    			$uniqid = getCurrentId();
    			$res = $mysqlTools->executeSql("
    					INSERT INTO `sys_user_role` (`id`, `userId`, `roleId`) VALUES ($uniqid, $userId, $condition[roleId])
    					");
    			if(!$res){
    				$result = false;
    			}
    		}
    	}
    	return $result;
    }
    
    /**
     * 删除角色用户
     */
    public function delRoleUser($condition){
    	global $mysqlTools;
    	//参数处理注入SQL安全问题
    	$result = true;
    	if(array_key_exists('del',$condition) && empty($condition['del'])){
    		return $result;
    	}
    	$list = explode(',',$condition['del']);
    	$condition = $mysqlTools->check_input($condition);
    	if(!empty($condition['del'])){
    		foreach ($list as $userId){
    			$res = $mysqlTools->executeSql("
    					DELETE FROM `sys_user_role`
    					WHERE `userId` = $userId AND `roleId` = $condition[roleId]
    					");
    			if(!$res){
    				$result = false;
    			}
    		}
    	}
    	return $result;
    }
    
    /**
     * 删除角色
     */
    public function delRole($condition){
    	global $mysqlTools;
    	//参数处理注入SQL安全问题
    	$condition = $mysqlTools->check_input($condition);
    	try {
    		$mysqlTools->startTransaction();
    		$result = $mysqlTools->executeSql("
    			DELETE FROM `sys_role`
				WHERE `id` = $condition[id]
    		");
    		$mysqlTools->commitTransaction();
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    	}
    	return $result;
    }
    
    /**
     * 查询名称是否存在
     */
    public function checkRoleName($condition){
    	global $mysqlTools;
    	//参数处理注入SQL安全问题
    	$condition = $mysqlTools->check_input($condition);
    	try {
    		$mysqlTools->startTransaction();
    		$result = $mysqlTools->selectSql("
    				SELECT COUNT(*) as count FROM `sys_role`
    				WHERE `name` = $condition[name]
    				")[0]['count'];
    		$mysqlTools->commitTransaction();
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return false;
    	}
    	return $result==0;
    }
    
    /**
     * 处理菜单操作
     */
    public function processRoleMenus($condition)
    {
    	global $mysqlTools;
    	try {
	    	$mysqlTools->startTransaction();
	    	$result = $this->addRoleMenu($condition) && $this->delRoleMenu($condition);
	    	if($result){
	    		$mysqlTools->commitTransaction();
	    	}else{
	    		$mysqlTools->rollback();
	    	}
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return $result;
    	}
    	return $result;
    }
    
    /**
     * 处理角色用户操作
     */
    public function processRoleUsers($condition)
    {
    	global $mysqlTools;
    	try {
    		$mysqlTools->startTransaction();
    		$result = $this->addRoleUser($condition) && $this->delRoleUser($condition);
    		if($result){
    			$mysqlTools->commitTransaction();
    		}else{
    			$mysqlTools->rollback();
    		}
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return $result;
    	}
    	return $result;
    }
    
    

}	

?>